package org.jflame.auth.authz;

import org.jflame.commons.util.CollectionHelper;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

public class SimpleRole implements Serializable {

    private static final long serialVersionUID = 6233094199966293498L;
    private String roleCode;
    protected Set<Permit> permissions;

    public SimpleRole() {
    }

    public SimpleRole(String roleCode) {
        this.roleCode = roleCode;
    }

    public SimpleRole(String roleCode, Set<Permit> permissions) {
        this.roleCode = roleCode;
        this.permissions = permissions;
    }

    public String getRoleCode() {
        return roleCode;
    }

    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }

    public Set<Permit> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<Permit> permissions) {
        this.permissions = permissions;
    }

    public void addPermission(Permit permission) {
        if (permission != null) {
            if (CollectionHelper.isEmpty(permissions)) {
                permissions = new LinkedHashSet<>();
            }
            permissions.add(permission);
        }
    }

    public void addPermissions(Collection<? extends Permit> perms) {
        if (CollectionHelper.isEmpty(perms)) {
            if (permissions == null) {
                permissions = new LinkedHashSet<>(perms.size());
            }
            permissions.addAll(perms);
        }
    }

    public boolean isPermitted(Permit p) {
        Set<Permit> perms = getPermissions();
        if (CollectionHelper.isNotEmpty(perms)) {
            for (Permit perm : perms) {
                if (perm.implies(p)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(roleCode);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SimpleRole other = (SimpleRole) obj;
        return Objects.equals(roleCode, other.roleCode);
    }

}
